package com.example.administrator.xinyutg.utils;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.List;

/**
 * Created by Administrator on 2015/9/26.
 */
public class FragmentUtil implements RadioGroup.OnCheckedChangeListener {
    private List<Fragment> list;
    private RadioGroup rg;
    private FragmentManager fm;
    private int containerViewId;

    public FragmentUtil(List<Fragment> list, int containerViewId, FragmentManager fm, RadioGroup rg) {
        this.list = list;
        this.containerViewId = containerViewId;
        this.fm = fm;
        this.rg = rg;
        rg.setOnCheckedChangeListener(this);
        //默认第一个为选中状态
        RadioButton button = (RadioButton) rg.getChildAt(0);
        button.setChecked(true);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        for (int i = 0; i < group.getChildCount(); i++) {
            Fragment fragment = list.get(i);
            //如果被选中，就将对应的fragment加入到回退栈
            if (checkedId == group.getChildAt(i).getId()) {
                if (!fragment.isAdded()) {
                    fm.beginTransaction().add(containerViewId, fragment).commit();
                }
                fm.beginTransaction().show(fragment).commit();
            } else {
                //隐藏位选中的fragment
                fm.beginTransaction().hide(fragment).commit();
            }
        }


    }


}
